package com.roc.web.action;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.OperatorAuth;
import com.roc.pojo.Operators;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.service.operator.OperatorReceiveService;
import com.roc.util.Constance;
import com.roc.util.HttpUtil;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.AuthReason;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/operatorAuthCheck")
public class OperatorAuthCheckAction extends PaginationBaseAction {
	
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 7635674482684103845L;
	
	private Logger logger=LogManager.getLogger(OperatorAuthCheckAction.class);
	
	private OperatorAuthCheckSearchCondition searchCondition;
	private String OperatorAuthIdList;
	private String authIdList;
	private Long detailId;
	private Long receiveId;
	private String status;
	private String fileName;
	private String resultDetail;
	private String accountNo;
	private String realName;
	private String idCard;
	private String resultTrueDetail;
	private String resultLimitDetail;
	private String releaseLimitDetail; //解限备注
	private String releaseLimitProveImgUrl; //担保函照片
	private OperatorAuth operatorAuth;
	private String endDate;
	private String startDate;
	private String updateFlag;
	
	
	@Autowired
	IPageService pageService;
	
	@Autowired
	private OperatorReceiveService operatorReceiveService;
	
	@Autowired
	IMerchantServices merinfoService;
	private String isAllowToReleLimit; //解限权限
	
	/**
	 * 跳转实名审核领件页面
	 * */
	@Action(value="toList",results={@Result(name=SUCCESS,location="/pages/operator/operatorAuthCheckList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String returnCollarPiecesJsp(){
		try {
			 Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	         if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
				 addActionError("无权限访问");
				 return ERROR;
			 }
		} catch (Exception e) {
			logger.error("跳转实名审核领件页面出错");
		}
		return SUCCESS;
	}

	/**
	 * 查询领件
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryOperatorsAuthCheck", 
			results = { @Result(name = "success", location = "/pages/operator/operatorAuthCheckList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryOperatorAuthCheck() throws Exception{
       
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		try {
			if(!op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) &&
					   !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())	){
					addActionError("无此权限");
						return SUCCESS;
			}
			if (searchCondition == null) {
				searchCondition = (OperatorAuthCheckSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new OperatorAuthCheckSearchCondition();
				}
			}

			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || 
			   op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())  ){
				searchCondition.setOperatorId(op.getId());
				handleResultListForCollarPieces(op);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
			return SUCCESS;
	}
	
	/**
	 * 实名认证详情
	 * @return
	 */
	@Action(value="operatorAuthInfo", results = {
			@Result(name = SUCCESS, location = "/pages/operator/operatorAuthCheck.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String operatorAuthInfo(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try {
			OperatorAuth operatorAuth = operatorReceiveService.queryOperatorAuthById(op, receiveId,detailId);
			getRequest().setAttribute("operatorAuth",operatorAuth);
			getRequest().setAttribute("auditingMap",ConfigMerinfoUtil.getAppAuditingMap());//审核
			getRequest().setAttribute("authReasonList",AuthReason.getAllEnumMap());//审核
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 实名认证详情show
	 * @return
	 */
	@Action(value="operatorAuthInfoShow", results = {
			@Result(name = SUCCESS, location = "/pages/operator/operatorAuthCheckShow.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String operatorAuthInfoShow(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try {
			OperatorAuth operatorAuth = operatorReceiveService.queryOperatorAuthById(op, receiveId,detailId);
			if(StringUtils.isEmpty(updateFlag)&&"0".equals(updateFlag)){
				getRequest().setAttribute("updateFlag",true);
			}
			getRequest().setAttribute("operatorAuth",operatorAuth);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 实名认证解限详情页面
	 */
	@Action(value="operatorAuthReleaseLimit", results = {
			@Result(name = SUCCESS, location = "/pages/operator/operatorAuthReleaseLimit.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String operatorAuthReleaseLimit(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if("1".equals(isAllowToReleLimit)){
				OperatorAuth operatorAuth = operatorReceiveService.queryOperatorAuthById(op, receiveId,detailId);
				getRequest().setAttribute("operatorAuth",operatorAuth);
			}else{
				addActionError("无权限访问");
				return SUCCESS;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 审核实名认证
	 * @return
	 */
	@Action(value="checkReceive", results = {
			@Result(name = SUCCESS, location = "/pages/operator/operatorAuthCheckList.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String checkReceive(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		try {
			logger.info(op.getRealName()+"开始审核领取的付临门会员实名认证,主键是："+receiveId);
			if(AuditingResultCodeType.PASS.getCode().equals(status)){
				resultDetail = resultTrueDetail;
			}else if(AuditingResultCodeType.AUTH_LIMIT.getCode().equals(status)){
				resultDetail = resultLimitDetail;
			}
			String rtnStrtus =operatorReceiveService.updateReceiveInfo(op, receiveId, status,resultDetail);
			if(AuditingResultCodeType.PASS.getCode().equals(rtnStrtus)){
				addActionMessage("审核通过");
			}else if(AuditingResultCodeType.REFUSE.getCode().equals(rtnStrtus)){
				addActionMessage("驳回审核");
			}else if(AuditingResultCodeType.AUTH_LIMIT.getCode().equals(rtnStrtus)){
				addActionMessage("审核限制");
			}else{
				addActionMessage("未知状态");
			}
		} catch (Exception e) {
			logger.error("提交异常");
			logger.error(e.getMessage(),e);
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 处理查询结果
	 * @throws Exception 
	 * @throws ServiceException 
	 * */
	private void handleResultListForCollarPieces(Operators  op) throws Exception {
		try {
			int rows = pageService.countSQL(searchCondition);
			List<OperatorAuth> msList = new ArrayList<OperatorAuth>();
			if (rows > 0) {
				searchRsList = pageService.findAllSQL(searchCondition, 
													calcuStart(getCurrentPage()),
													Constance.PAGE_MAX_SIZE);
				if(searchRsList!=null&&searchRsList.size()>0){
					msList = handleDetail(searchRsList);
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);//统计次数
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception("查询失败",e);
		}
	}
	
	@Action(value="showPhone")
	public void showPhone(){
		try{
			if(StringUtils.isNotEmpty(fileName)){
				getResponse().setContentType("image/jpg");
				String path = Utils.getConfigValue("sfb_img_domain") + Utils.getConfigValue("FTP_REMOTE_FILEPATH") +"/"+ Utils.getConfigValue("REALNAMR_AUTH") +"/"+accountNo + "/"+ fileName;
				logger.info("图片地址："+path);
				CloseableHttpClient httpclient = HttpClients.createDefault();
				HttpGet httpGet = new HttpGet(path);
				HttpResponse response = httpclient.execute(httpGet);
				InputStream in = response.getEntity().getContent();
				ServletOutputStream outputStream = getResponse().getOutputStream();
				IOUtils.copy(in, outputStream);
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
	}
	
	@Action(value="updateIdCardDate")
	public void updateIdCardDate(){
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			OperatorAuth operatorAuth = operatorReceiveService.queryOperatorAuthById(op, receiveId, (long) 0);
			operatorAuth.setExt1(startDate);
			operatorAuth.setExt2(endDate);
			operatorReceiveService.updateIdCardDate(op,operatorAuth);
			json.put("msgCode", "0000");
			json.put("msgText", "修改成功");
			pw.write(json.toString());
						
		} catch (Exception e) {
			logger.error("验证异常");
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
	
	@Action(value="yzIdCard")
	public void yzIdCard(){
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			String url = Utils.getConfigValue("CREDIT_CK");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("type", "idCard");
			jsonObject.put("name", realName);
			jsonObject.put("citizenIdNumber", idCard);
			logger.info("============调用验证身份证合法性接口开始============");
			String	result = HttpUtil.sendGetOrPostR(url, jsonObject.toString());
			logger.info("============调用验证证件合法性接口结束============");
			JSONObject resp = JSONObject.fromObject(result);
			String msgCode = resp.getString("msg_code");
			String msgText = resp.getString("msg_text");
			json.put("msgCode", msgCode);
			json.put("msgText", msgText);
			if("00".equals(msgCode)){
				String photos = resp.getString("photos");
				json.put("photos", photos);
			}
			pw.write(json.toString());
						
		} catch (Exception e) {
			logger.error("验证异常");
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
	
	private List<OperatorAuth> handleDetail(List<Object> objList) throws Exception{
		List<OperatorAuth> list = new ArrayList<OperatorAuth>();
		Iterator iterator = objList.iterator();
		while (iterator.hasNext()) {
			OperatorAuth operatorAuth = new OperatorAuth();
			Object[] obj = (Object[]) iterator.next();
			operatorAuth.setReceiveId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
			operatorAuth.setAccountNo(Constance.Null2EmptyTrim(obj[1]));
			operatorAuth.setUserName(Constance.Null2EmptyTrim(obj[2]));
			operatorAuth.setCardNo(Constance.Null2EmptyTrim(obj[4]));
			operatorAuth.setCardType(Constance.Null2EmptyTrim(obj[3]));
			operatorAuth.setCreateAtStr(Constance.Null2EmptyTrim(obj[9]));
			operatorAuth.setCreateAtStrR(Constance.Null2EmptyTrim(obj[10]));
			operatorAuth.setExt1(Constance.Null2EmptyTrim(obj[11]));
			operatorAuth.setExt2(Constance.Null2EmptyTrim(obj[12]));
			list.add(operatorAuth);
		}
		return list;
		
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_OPERATOR_AUTH_CHECK, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (OperatorAuthCheckSearchCondition) getSession().getAttribute(SEARCH_SESSION_OPERATOR_AUTH_CHECK);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	

	public OperatorAuthCheckSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(OperatorAuthCheckSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getOperatorAuthIdList() {
		return OperatorAuthIdList;
	}

	public void setOperatorAuthIdList(String operatorAuthIdList) {
		OperatorAuthIdList = operatorAuthIdList;
	}

	public OperatorReceiveService getOperatorReceiveService() {
		return operatorReceiveService;
	}

	public void setOperatorReceiveService(
			OperatorReceiveService operatorReceiveService) {
		this.operatorReceiveService = operatorReceiveService;
	}

	public String getAuthIdList() {
		return authIdList;
	}

	public void setAuthIdList(String authIdList) {
		this.authIdList = authIdList;
	}

	public Long getReceiveId() {
		return receiveId;
	}

	public void setReceiveId(Long receiveId) {
		this.receiveId = receiveId;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getResultDetail() {
		return resultDetail;
	}

	public void setResultDetail(String resultDetail) {
		this.resultDetail = resultDetail;
	}

	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public String getIdCard() {
		return idCard;
	}

	public void setIdCard(String idCard) {
		this.idCard = idCard;
	}

	public Long getDetailId() {
		return detailId;
	}

	public void setDetailId(Long detailId) {
		this.detailId = detailId;
	}

	public String getResultTrueDetail() {
		return resultTrueDetail;
	}

	public void setResultTrueDetail(String resultTrueDetail) {
		this.resultTrueDetail = resultTrueDetail;
	}

	public String getResultLimitDetail() {
		return resultLimitDetail;
	}

	public void setResultLimitDetail(String resultLimitDetail) {
		this.resultLimitDetail = resultLimitDetail;
	}

	public String getReleaseLimitDetail() {
		return releaseLimitDetail;
	}

	public void setReleaseLimitDetail(String releaseLimitDetail) {
		this.releaseLimitDetail = releaseLimitDetail;
	}

	public String getIsAllowToReleLimit() {
		return isAllowToReleLimit;
	}

	public void setIsAllowToReleLimit(String isAllowToReleLimit) {
		this.isAllowToReleLimit = isAllowToReleLimit;
	}

	public String getReleaseLimitProveImgUrl() {
		return releaseLimitProveImgUrl;
	}

	public void setReleaseLimitProveImgUrl(String releaseLimitProveImgUrl) {
		this.releaseLimitProveImgUrl = releaseLimitProveImgUrl;
	}

	public OperatorAuth getOperatorAuth() {
		return operatorAuth;
	}

	public void setOperatorAuth(OperatorAuth operatorAuth) {
		this.operatorAuth = operatorAuth;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getUpdateFlag() {
		return updateFlag;
	}

	public void setUpdateFlag(String updateFlag) {
		this.updateFlag = updateFlag;
	}
	
}